﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "新增BOM";
}
<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />

<script src="~/layui/layui.js"></script>
<script src="~/js/site.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>

<div class="layui-container" style="padding: 20px;">
    <div class="layui-row">
        <div class="layui-col-md12">
            <h2>新增BOM</h2>
        </div>
    </div>
    
    <!-- 新增BOM表单 -->
    <div class="layui-row">
        <div class="layui-col-md8 layui-col-md-offset2">
            <form class="layui-form" id="addBOMForm">
                <div class="layui-form-item">
                    <label class="layui-form-label">BOM主题</label>
                    <div class="layui-input-block">
                        <input type="text" name="BOMtheme" lay-verify="required" placeholder="请输入BOM主题" autocomplete="off" class="layui-input">
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label">BOM版本</label>
                    <div class="layui-input-block">
                        <input type="text" name="BOMVersion" lay-verify="required" placeholder="请输入BOM版本" autocomplete="off" class="layui-input">
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label">产品选择</label>
                    <div class="layui-input-block">
                        <select name="productId" lay-verify="required" lay-search>
                            <option value="">请选择产品</option>
                        </select>
                    </div>
                </div>
                

                
                <div class="layui-form-item">
                    <label class="layui-form-label">天数</label>
                    <div class="layui-input-block">
                        <input type="number" name="dayNum" lay-verify="required|number" placeholder="请输入天数" autocomplete="off" class="layui-input">
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label">BOM描述</label>
                    <div class="layui-input-block">
                        <textarea name="BOMDesc" lay-verify="required" placeholder="请输入BOM描述" class="layui-textarea"></textarea>
                    </div>
                </div>
                

                
                <div class="layui-form-item">
                    <label class="layui-form-label">BOM状态</label>
                    <div class="layui-input-block">
                        <input type="checkbox" name="bomState" lay-skin="primary" title="启用" checked>
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="addBOMSubmit">
                            <i class="layui-icon layui-icon-ok"></i> 提交
                        </button>
                        <button type="reset" class="layui-btn layui-btn-primary">
                            <i class="layui-icon layui-icon-refresh"></i> 重置
                        </button>
                        <button type="button" class="layui-btn layui-btn-warm" id="backToList">
                            <i class="layui-icon layui-icon-left"></i> 返回列表
                        </button>
                                    <a href="/Home/Index" class="layui-btn layui-btn-primary">
                <i class="layui-icon layui-icon-home"></i> 返回主页
            </a>
                       
                    </div>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 物料列表区域 -->
    <div class="layui-row" style="margin-top: 30px;">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <h3>物料配件列表</h3>
                </div>
                <div class="layui-card-body">
                    <table id="materialTable" lay-filter="materialTable"></table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
layui.use(['form', 'layer', 'table'], function(){
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    

    
    // 初始化物料表格
    function initMaterialTable() {
        $.ajax({
            url: 'http://localhost:5025/api/BOM/GetMaterial',
            type: 'GET',
            success: function(response) {
                console.log('获取物料数据成功:', response);
                if (response.code === 200 && response.data) {
                    table.render({
                        elem: '#materialTable',
                        data: response.data,
                        page: true,
                        cols: [[
                            {type: 'checkbox', fixed: 'left'},
                            {field: 'materialId', title: '物料ID', width: 100, sort: true},
                            {field: 'materialName', title: '物料名称', width: 150},
                            {field: 'specification', title: '规格型号', width: 200},
                            {field: 'unitName', title: '单位', width: 80},
                            {field: 'brand', title: '品牌', width: 120},
                            {field: 'partNum', title: '配件数量', width: 120, templet: function(d){
                                return '<input type="number" class="layui-input part-num-input" data-id="'+d.materialId+'" placeholder="请输入" style="width:80px;">';
                            }},
                            {field: 'lossRate', title: '损耗率', width: 120, templet: function(d){
                                return '<input type="text" class="layui-input loss-rate-input" data-id="'+d.materialId+'" placeholder="请输入" style="width:80px;">';
                            }}
                        ]],
                        limits: [15, 30, 50, 100],
                        limit: 15,
                        height: 400,
                        done: function(res, curr, count) {
                            console.log('物料表格渲染完成:', res);
                            console.log('当前页:', curr);
                            console.log('总数据量:', count);
                        }
                    });
                } else {
                    console.error('物料数据格式错误:', response);
                }
            },
            error: function(xhr, status, error) {
                console.error('获取物料数据失败:', error);
            }
        });
    }
    
    // 调用初始化函数
    initMaterialTable();
    
    // 初始化产品下拉框
    function initProductSelect() {
        $.ajax({
            url: 'http://localhost:5025/api/BOM/GetProduct',
            type: 'GET',
            success: function(response) {
                console.log('获取产品数据成功:', response);
                if (response.code === 200 && response.data) {
                    var select = $('select[name="productId"]');
                    select.empty();
                    select.append('<option value="">请选择产品</option>');
                    
                    response.data.forEach(function(product) {
                        select.append('<option value="' + product.productId + '">' + 
                                    product.productName + ' (' + product.productType + ')</option>');
                    });
                    
                    // 重新渲染表单
                    form.render('select');
                    console.log('产品下拉框初始化完成');
                } else {
                    console.error('产品数据格式错误:', response);
                }
            },
            error: function(xhr, status, error) {
                console.error('获取产品数据失败:', error);
            }
        });
    }
    
    // 调用产品初始化函数
    initProductSelect();
    

    
    // 更新材料ID字段（已废弃，现在直接使用表格选中状态）
    function updateMaterialIdField(){
        // 此函数已不再使用，保留是为了兼容性
    }
    
    // 表单提交事件
    form.on('submit(addBOMSubmit)', function(data){
        var formData = data.field;
        
        console.log('表单原始数据:', formData);
        console.log('表单字段检查:');
        console.log('- BOMtheme:', formData.BOMtheme, '类型:', typeof formData.BOMtheme);
        console.log('- BOMVersion:', formData.BOMVersion, '类型:', typeof formData.BOMVersion);
        console.log('- BOMDesc:', formData.BOMDesc, '类型:', typeof formData.BOMDesc);
        
        // 处理复选框值
        formData.bomState = formData.bomState === 'on' || formData.bomState === true;
        
        // 获取表格中选中的物料
        var checkStatus = table.checkStatus('materialTable');
        var selectedTableData = checkStatus.data;
        
        if(selectedTableData.length === 0){
            layer.msg('请至少选择一个物料', {icon: 2});
            return false;
        }
        
        // 获取每个选中物料的配件数量和损耗率
        var materials = [];
        for(var i = 0; i < selectedTableData.length; i++){
            var item = selectedTableData[i];
            var partNumInput = $('.part-num-input[data-id="'+item.materialId+'"]');
            var lossRateInput = $('.loss-rate-input[data-id="'+item.materialId+'"]');
            
            // 检查配件数量和损耗率是否已填写
            var partNum = partNumInput.val();
            var lossRate = lossRateInput.val();
            
            if(!partNum || partNum.trim() === ''){
                layer.msg('请填写物料 "' + item.materialName + '" 的配件数量', {icon: 2});
                return false;
            }
            
            if(!lossRate || lossRate.trim() === ''){
                layer.msg('请填写物料 "' + item.materialName + '" 的损耗率', {icon: 2});
                return false;
            }
            
            materials.push({
                materialId: item.materialId,
                partNum: parseInt(partNum),
                lossRate: lossRate.trim()
            });
        }
        
        // 确保所有必需字段都有值，并检查是否为空字符串
        var requestData = {
            bomTheme: formData.BOMtheme && formData.BOMtheme.trim() !== '' ? formData.BOMtheme.trim() : '',
            bomVersion: formData.BOMVersion && formData.BOMVersion.trim() !== '' ? formData.BOMVersion.trim() : '',
            productId: parseInt(formData.productId) || 0,
            materials: materials, // 使用包含配件数量和损耗率的物料信息
            dayNum: parseInt(formData.dayNum) || 0,
            bomDesc: formData.BOMDesc && formData.BOMDesc.trim() !== '' ? formData.BOMDesc.trim() : '',
            bomState: formData.bomState || false
        };
        
        // 如果表单值为空，尝试从DOM元素获取
        if (!formData.BOMtheme || formData.BOMtheme.trim() === '') {
            formData.BOMtheme = $('input[name="BOMtheme"]').val() || '';
        }
        if (!formData.BOMVersion || formData.BOMVersion.trim() === '') {
            formData.BOMVersion = $('input[name="BOMVersion"]').val() || '';
        }
        if (!formData.BOMDesc || formData.BOMDesc.trim() === '') {
            formData.BOMDesc = $('textarea[name="BOMDesc"]').val() || '';
        }
        
        console.log('修正后的表单数据:', formData);
        
        // 显示加载层
        var loadIndex = layer.load(1, {
            shade: [0.1,'#fff']
        });
        
        // 发送Ajax请求
        $.ajax({
            url: 'http://localhost:5025/api/BOM/AddBOM',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(requestData),
            success: function(response){
                layer.close(loadIndex);
                
                if(response.code === 200){
                    layer.msg('新增BOM成功！', {
                        icon: 1,
                        time: 2000
                    }, function(){
                        // 成功后直接刷新页面内容
                        refreshPageContent();
                    });
                } else {
                    layer.msg(response.msg || '新增失败：' + response.code, {
                        icon: 2,
                        time: 3000
                    });
                }
            },
            error: function(xhr, status, error){
                layer.close(loadIndex);
                
                console.error('Ajax请求失败:', xhr.responseText);
                console.error('状态码:', xhr.status);
                console.error('错误信息:', error);
                
                // 尝试解析错误响应
                try {
                    var errorResponse = JSON.parse(xhr.responseText);
                    if (errorResponse.errors) {
                        var errorMessages = [];
                        for (var field in errorResponse.errors) {
                            errorMessages.push(field + ': ' + errorResponse.errors[field].join(', '));
                        }
                        layer.msg('验证失败：' + errorMessages.join('; '), {
                            icon: 2,
                            time: 5000
                        });
                    } else {
                        layer.msg('请求失败：' + (errorResponse.title || error), {
                            icon: 2,
                            time: 3000
                        });
                    }
                } catch (e) {
                    layer.msg('请求失败：' + error, {
                        icon: 2,
                        time: 3000
                    });
                }
            }
        });
        
        return false; // 阻止表单默认提交
    });
    
    // 返回列表按钮
    $('#backToList').on('click', function(){
        window.location.href = '/Home/GetBOM';
    });
    
    // 自定义验证规则
    form.verify({
        // 可以添加自定义验证规则
        productId: function(value, item){
            if(!value || value === ''){
                return '请选择产品';
            }
        },

        dayNum: function(value, item){
            if(value <= 0){
                return '天数必须大于0';
            }
        },
        partNum: function(value, item){
            if(value <= 0){
                return '零件数量必须大于0';
            }
        }
    });
    
    // 页面加载完成后的初始化
    $(document).ready(function(){
        
        // 测试API连接
        $.ajax({
            url: 'http://localhost:5025/api/BOM/GetMaterial',
            type: 'GET',
            success: function(response) {
                console.log('物料API测试成功:', response);
            },
            error: function(xhr, status, error) {
                console.error('物料API测试失败:', error);
            }
        });
        
        // 测试产品API连接
        $.ajax({
            url: 'http://localhost:5025/api/BOM/GetProduct',
            type: 'GET',
            success: function(response) {
                console.log('产品API测试成功:', response);
            },
            error: function(xhr, status, error) {
                console.error('产品API测试失败:', error);
            }
        });
        
        // 监听配件数量和损耗率输入框的变化（用于实时验证）
        $(document).on('input', '.part-num-input, .loss-rate-input', function(){
            var materialId = $(this).data('id');
            var value = $(this).val();
            
            // 可以在这里添加实时验证逻辑
            console.log('物料ID:', materialId, '值:', value);
        });
    });
    
    // 刷新页面内容的函数
    function refreshPageContent() {
        // 重置表单
        $('#addBOMForm')[0].reset();
        form.render();
        
        // 清空物料表格
        table.reload('materialTable', {
            data: []
        });
        
        // 重新加载产品下拉框
        loadProducts();
        
        // 重新加载物料数据
        loadMaterials();
        
        layer.msg('页面已刷新，可以继续添加新的BOM', {
            icon: 1,
            time: 2000
        });
    }
    
    // 加载产品数据的函数
    function loadProducts() {
        $.ajax({
            url: 'http://localhost:5025/api/BOM/GetProduct',
            type: 'GET',
            success: function(response) {
                if(response.code === 200 && response.data) {
                    var productSelect = $('select[name="productId"]');
                    productSelect.empty();
                    productSelect.append('<option value="">请选择产品</option>');
                    
                    response.data.forEach(function(product) {
                        productSelect.append('<option value="' + product.productId + '">' + product.productName + '</option>');
                    });
                    
                    form.render('select');
                }
            },
            error: function(xhr, status, error) {
                console.error('加载产品数据失败:', error);
            }
        });
    }
    
    // 加载物料数据的函数
    function loadMaterials() {
        $.ajax({
            url: 'http://localhost:5025/api/BOM/GetMaterial',
            type: 'GET',
            success: function(response) {
                if(response.code === 200 && response.data) {
                    table.reload('materialTable', {
                        data: response.data
                    });
                }
            },
            error: function(xhr, status, error) {
                console.error('加载物料数据失败:', error);
            }
        });
    }
});
</script>

<style>
.layui-form {
    margin-top: 20px;
}

.layui-form-label {
    width: 100px;
}

.layui-input-block {
    margin-left: 130px;
}

.layui-textarea {
    min-height: 80px;
}

.layui-btn {
    margin-right: 10px;
}

.layui-container {
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    margin-top: 20px;
}

h2 {
    color: #333;
    border-bottom: 2px solid #5FB878;
    padding-bottom: 10px;
}

.layui-card {
    margin-top: 20px;
}

.layui-card-header {
    background-color: #f8f8f8;
    border-bottom: 1px solid #e6e6e6;
    padding: 15px 20px;
}

.layui-card-header h3 {
    margin: 0;
    color: #333;
    font-size: 16px;
    font-weight: bold;
}

.layui-card-body {
    padding: 20px;
}

.part-num-input, .loss-rate-input {
    border: 1px solid #e6e6e6;
    border-radius: 2px;
    padding: 5px 8px;
    font-size: 12px;
}

.part-num-input:focus, .loss-rate-input:focus {
    border-color: #5FB878;
    box-shadow: 0 0 0 2px rgba(95, 184, 120, 0.2);
}
</style>